
using System;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ScrewTurn.Wiki.PluginFramework;
using System.Collections.Generic;

namespace ScrewTurn.Wiki {

	public partial class Register : BasePage {
		
		#region Initialization

        protected void Page_Load(object sender, EventArgs e) {

			// Test whether the default Users Provider is read-only
			IUsersStorageProvider p = Collectors.UsersProviderCollector.GetProvider(Settings.DefaultUsersProvider);
			if(p.ReadOnly) {
				Log.LogEntry("Default Users Provider (" + p.Information.Name + ") is read-only, aborting Account Creation", EntryType.Warning, "SYSTEM");
				Response.Redirect("Error.aspx");
			}

            Page.Title = Resources.Messages.RegisterTitle + " - " + Settings.WikiTitle;

			if(!Settings.UsersCanRegister) {
				if((SessionFacade.LoginKey != null && !SessionFacade.Admin) || SessionFacade.LoginKey == null)
					Response.Redirect("AccessDenied.aspx");
			}

			switch(Settings.AccountActivationMode.ToLowerInvariant()) {
				case "email":
					lblAccountActivationMode.Text = Resources.Messages.ActivationEmail;
					break;
				case "admin":
					lblAccountActivationMode.Text = Resources.Messages.ActivationAdmin;
					break;
				case "auto":
					lblAccountActivationMode.Text = Resources.Messages.ActivationAuto;
					break;
			}

			if(Settings.DisableCaptchaControl) {
				lblCaptcha.Visible = false;
				captcha.Visible = false;
			}

			if(!Page.IsPostBack) {
				LoadRegExp();
				LoadValidationLocalizations();
			}

		}

		private void LoadRegExp() {
			// Load RegExp's from Web.Config

			//User 
			rxvUserName.ValidationExpression = Settings.UsernameRegex;
			rxvEmail1.ValidationExpression = Settings.EmailRegex;
			rxvPassword1.ValidationExpression = Settings.PasswordRegex;
		}

		private void LoadValidationLocalizations() {
			//User validators
			rfvUsername.ErrorMessage = Resources.Messages.RequiredField;
			rfvUsername.ToolTip = Resources.Messages.RequiredField;
			rfvEmail1.ErrorMessage = Resources.Messages.RequiredField;
			rfvEmail1.ToolTip = Resources.Messages.RequiredField;
			rfvEmail2.ErrorMessage = Resources.Messages.RequiredField;
			rfvEmail2.ToolTip = Resources.Messages.RequiredField;
			rfvPassword1.ErrorMessage = Resources.Messages.RequiredField;
			rfvPassword1.ToolTip = Resources.Messages.RequiredField;
			rfvPassword2.ErrorMessage = Resources.Messages.RequiredField;
			rfvPassword2.ToolTip = Resources.Messages.RequiredField;

			rxvUserName.ErrorMessage = Resources.Messages.InvalidUsername;
			rxvUserName.ToolTip = Resources.Messages.InvalidUsername;
			rxvEmail1.ErrorMessage = Resources.Messages.InvalidEmail;
			rxvEmail1.ToolTip = Resources.Messages.InvalidEmail;
			rxvPassword1.ErrorMessage = Resources.Messages.InvalidPassword;
			rxvPassword1.ToolTip = Resources.Messages.InvalidPassword;

			cvUsername.ErrorMessage = Resources.Messages.UsernameAlreadyExists;
			cvUsername.ToolTip = Resources.Messages.UsernameAlreadyExists;
			cvEmail1.ErrorMessage = Resources.Messages.EmailsNotEqual;
			cvEmail1.ToolTip = Resources.Messages.EmailsNotEqual;
			cvEmail2.ErrorMessage = Resources.Messages.EmailsNotEqual;
			cvEmail2.ToolTip = Resources.Messages.EmailsNotEqual;

			cvPassword1.ErrorMessage = Resources.Messages.PasswordsNotEqual;
			cvPassword1.ToolTip = Resources.Messages.PasswordsNotEqual;
			cvPassword2.ErrorMessage = Resources.Messages.PasswordsNotEqual;
			cvPassword2.ToolTip = Resources.Messages.PasswordsNotEqual;
		}
		
		#endregion

		protected void btnRegister_Click(object sender, EventArgs e) {
			if (!Settings.UsersCanRegister) return;

			lblResult.Text = "";
			lblResult.CssClass = "";

			if(!Page.IsValid) return;

			// Ready to save the user
			Users u = Users.Instance;
			Log.LogEntry("Account creation requested for " + txtUsername.Text, EntryType.General, "SYSTEM");
			Users.Instance.AddUser(txtUsername.Text, txtPassword1.Text, txtEmail1.Text, Settings.AccountActivationMode.ToLowerInvariant().Equals("auto"), false, null);
			if(Settings.AccountActivationMode.ToLowerInvariant().Equals("email")) {
				string body = Tools.LoadFile(Settings.AccountActivationMessageFile);
				body = body.Replace("##WIKITITLE##", Settings.WikiTitle).Replace("##USERNAME##", txtUsername.Text).Replace("##EMAILADDRESS##", Settings.ContactEmail);
				body = body.Replace("##ACTIVATIONLINK##", Settings.MainUrl + "Login.aspx?Activate=" + Tools.ComputeSecuredUsernameHash(txtUsername.Text));
				EmailSender.Send(txtEmail1.Text, Settings.SenderEmail, "Account Activation - " + Settings.WikiTitle, body, false);
			}
			if(Settings.AccountActivationMode.ToLowerInvariant().Equals("admin")) {
				List<UserInfo> admins = Users.Instance.Administrators;
				string[] rec = new string[admins.Count];
				for(int i = 0; i < rec.Length; i++) {
					rec[i] = admins[i].Email;
				}
				EmailSender.SendMassEmail(rec, Settings.SenderEmail, Settings.WikiTitle + " - User Account Approval", "The User Account <" + txtUsername.Text + "> requires approval. Please visit the Administration page to view the Account's details using the link below.\r\n\r\n" + Settings.MainUrl + "Admin.aspx?ActivationMode=1", false);
			}

			lblResult.CssClass = "resultok";
			lblResult.Text = "<br /><br />" + Resources.Messages.AccountCreated;
			btnRegister.Enabled = false;
			pnlRegister.Visible = false;
		}

		#region Custom Validators
		
		protected void cvUsername_ServerValidate(object source, ServerValidateEventArgs args) {
			if(txtUsername.Text.ToLowerInvariant().Equals("admin") || txtUsername.Text.ToLowerInvariant().Equals("guest")) {
				args.IsValid = false;
			}
			else {
				UserInfo u = Users.Instance.Find(txtUsername.Text);
				if(u != null) {
					args.IsValid = false;
				}
			}
		}
		
		protected void cvPassword1_ServerValidate(object source, ServerValidateEventArgs args) {
			args.IsValid = (string.Compare(txtPassword1.Text, txtPassword2.Text, true) == 0);
		}
		
		protected void cvPassword2_ServerValidate(object source, ServerValidateEventArgs args) {
			args.IsValid = true;
		}
		
		protected void cvEmail1_ServerValidate(object source, ServerValidateEventArgs args) {
			args.IsValid = (string.Compare(txtEmail1.Text, txtEmail2.Text, true) == 0);
		}
		
		protected void cvEmail2_ServerValidate(object source, ServerValidateEventArgs args) {
			args.IsValid = true;
		}
		
		#endregion

	}

}
